import React, { useEffect, useState } from 'react';
import { features, useTablePipeline } from 'ali-react-table';
import { connect } from 'umi';
import { Button, Checkbox, DatePicker, Form, Select } from 'antd';
import _, { uniqBy } from 'lodash';
import moment from 'moment';

import { useTRState } from '#/utils/trHooks';
import { TjStation } from '@/pages/ETrade/components';
import { FileSearchOutlined, UploadOutlined } from '#/utils/antdIcons';
import { AntdBaseTable } from '@/base/TBaseTable';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { TRDefault, PageLoading } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts';

import { mediumColumns } from './helper';
import { queryDataList } from './services';
import Detail from './Detail';
import styles from './index.less';

const MediumLongStrategyReview = ({ power = [] }) => {
  const [state, setState] = useTRState({
    initialValues: {
      date: moment(),
    },
    dataSource: [],
    selectedKeys: [],
    regions: [],
    stations: [],
    stationTree: [],
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);
  const [form] = Form.useForm();

  useEffect(() => {
    if (power.length) {
      init(power);
    }
  }, [power]);

  //初始化表单参数
  const defaultInit = (_stations, _regions = []) => {
    const stationsIds = _stations
      .filter((item) => item.marketId === _regions?.[0]?.marketId)
      ?.map((item) => item?.stationId || '');
    getStationOptions(_regions?.[0]?.children);
    form.setFieldsValue({
      region: _regions?.[0]?.marketId,
      unit: stationsIds,
    });
    form.submit();
  };

  const init = (arr) => {
    const _stations = [];
    arr.forEach((x) => {
      // 公司
      (x?.children || []).forEach((y) => {
        // 省份
        (y?.children || []).forEach((z) => {
          // 场站
          _stations.push(z);
        });
      });
    });
    defaultInit(_stations, arr);
    setState({
      regions: arr,
      stations: _stations,
    });
  };

  const getStationOptions = (arr = []) => {
    form.setFieldsValue({ unit: [] });
    const _optionAll = _.flatten(arr.map((i) => i.children?.map((y) => y.stationId)));
    form.setFieldsValue({ unit: _optionAll });
    setState({
      stationTree: arr,
    });
  };

  const onExport = () => {
    const { dataSource, selectedKeys } = state;
    if (!dataSource.length) return;
    let exportData = [];
    exportData = exportData.concat(
      dataSource
        .filter((t) => !selectedKeys.length || selectedKeys.includes(t.id))
        .map((c) => mediumColumns.map(({ code }) => c[code])),
    );
    const params = {
      header: mediumColumns.map((c) => (c.name?.props ? c.name.props.children[0] : c.name)),
      data: exportData,
      filename: `合同转让收益复盘`,
    };
    export_json_to_excel(params);
  };

  const changeRegions = (v, opt) => {
    form.setFieldsValue({
      unit: [],
    });
    getStationOptions(opt.children);
  };

  const getNewDataSource = (data) => {
    return data.map((t, i) => ({
      ...t,
      id: i,
    }));
  };

  const fetchData = async (params) => {
    setState({
      dataSource: [],
    });
    setLoading(true);
    const res = await queryDataList(params).catch(() => setLoading(false));
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setState({
        dataSource: getNewDataSource(res?.data),
      });
    } else {
      setError(res?.message);
    }
  };

  const onFinish = (values) => {
    const params = {
      date: moment(values.date).format('YYYY-MM'),
      provinceId: power.find((i) => i.marketId === values.region).provinceId,
      stationIds: values.unit,
    };
    fetchData(params);
  };

  const reset = () => {
    form.resetFields();
    defaultInit(state.stations, state.regions);
  };

  const showDetail = async (record) => {
    await Detail.show({ title: '策略详情', selectData: record });
  };

  const getColumns = () => {
    mediumColumns[0].render = (v, r) =>
      v === '合计' ? (
        v + `(${state.selectedKeys.length}项/${state.dataSource.length}项)`
      ) : (
        <div
          style={{
            display: 'flex',
            justifyContent: 'flex-start',
          }}
        >
          {v}
          <div
            style={{ marginLeft: '10px', color: '#18A0FB', cursor: 'pointer' }}
            onClick={() => {
              showDetail(r);
            }}
          >
            <FileSearchOutlined />
          </div>
        </div>
      );
    return mediumColumns;
  };

  const changeSelectKeys = (v) => {
    setState({
      selectedKeys: v,
    });
  };

  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({
      dataSource: state.dataSource,
      columns: getColumns(),
    })
    .primaryKey('id')
    .use(
      features.multiSelect({
        value: state.selectedKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: changeSelectKeys,
      }),
    );

  const renderContent = () => {
    if (loading) return <PageLoading />;
    if (error) return <TRDefault type="error" message={error} />;
    if (!state.dataSource.length) return <TRDefault type="empty" />;
    return (
      <AntdBaseTable
        useVirtual={{ horizontal: true, vertical: true, header: false }}
        key="id"
        style={{
          '--row-height': '28px',
          // '--header-bgcolor': '#383C3E',
          '--header-row-height': '28px',
          '--cell-padding': '4px 16px',
          '--cell-border-vertical': '1px solid #4E5154',
          '--header-cell-border-vertical': '1px solid #4E5154',
          '--bgcolor': '#2222629',
          '--hover-bgcolor': '#2222629',
          '--highlight-bgcolor': '#2222629',
        }}
        {...pipeline.getProps()}
      />
    );
  };

  return (
    <div className={styles.body}>
      <div className={styles.search}>
        <div className={styles.head}>
          <Form
            className={styles.form}
            form={form}
            initialValues={state.initialValues}
            onFinish={onFinish}
          >
            <Form.Item name="region">
              <Select
                options={state.regions}
                style={{ width: 200 }}
                placeholder="请选择交易中心"
                showSearch={true}
                onChange={changeRegions}
              />
            </Form.Item>
            <Form.Item name="unit" className={styles.searchEl}>
              <TjStation options={state.stationTree} />
            </Form.Item>
            <Form.Item name="date" className={styles.searchEl}>
              <DatePicker picker="month" format={'YYYYMM'} style={{ width: 200 }} />
            </Form.Item>
            <Button type="primary" htmlType="submit" className={styles.searchEl}>
              查询
            </Button>
            <Button className={styles.searchEl} onClick={reset} ghost>
              重置
            </Button>
          </Form>
        </div>
        <div>
          <Button type="link" icon={<UploadOutlined />} onClick={onExport}>
            导出
          </Button>
        </div>
      </div>
      <div className={styles.content}>{renderContent()}</div>
    </div>
  );
};

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  buttonPermissions: global.configure.buttonPermissions,
}))(MediumLongStrategyReview);
